package com.springboot.interceptor;

import com.alibaba.fastjson.JSONException;
import com.springboot.common.Constants;
import com.springboot.dto.Result;
import com.springboot.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理器,处理新增的异常，对于有特殊逻辑的返回直接定义个新方法，参考ServiceException
 */
@ControllerAdvice
@Component
@ResponseBody
public class GlobalExceptionHandler {

    private final static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(ServiceException.class)
    public Result<String> handlerServiceException(ServiceException e){
        LOGGER.error("非法的JSON报文,请仔细检查", e);
        return new Result<>(Constants.ERROR, e.getMessage(), "", "", e.getCode());
    }

    //定义json报文解析异常。
    @ExceptionHandler(JSONException.class)
    public Result<String> handlerJsonParserException(JSONException e){
        LOGGER.error("非法的JSON报文,请仔细检查", e);
        return new Result<>(Constants.ERROR, "非法的JSON报文,请仔细检查", "",  "", "500");
    }

    @ExceptionHandler(Exception.class)
    public Result<String> handlerException(Exception e){
        LOGGER.error("Oops", e);
        return new Result<>(Constants.ERROR, "服务器错误", "", "","500");
    }
}
